﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using smartphone.App_Code;
using System.Data;
using System.Data.Common;
using System.Text.RegularExpressions;


namespace smartphone.UserControls
{
    public partial class ProductsInManufacturer : System.Web.UI.UserControl
    {
        Product product = new Product();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ListItem item1, item2, item3, item4;
                string url = HttpContext.Current.Request.Url.AbsolutePath.ToString();
                if (url == "/Home.aspx" || url == "/KhuyenMai.aspx")
                {
                    // trang chu co dang "/Home.aspx" nen phai dat duong dan kieu nay
                    //string a = HttpContext.Current.Request.Url.AbsolutePath.ToString(); -->> lay dung dan hien tai
                    item1 = new ListItem("Theo tên từ A-Z", "?orderby=tenSanPham&orderway=asc");
                    item2 = new ListItem("Theo tên từ Z-A", "?orderby=tenSanPham&orderway=desc");
                    item3 = new ListItem("Theo giá tăng dần", "?orderby=donGia&orderway=asc");
                    item4 = new ListItem("Theo giá giảm dần", "?orderby=donGia&orderway=desc");

                }
                else
                {
                    item1 = new ListItem("Theo tên từ A-Z", "&orderby=tenSanPham&orderway=asc");
                    item2 = new ListItem("Theo tên từ Z-A", "&orderby=tenSanPham&orderway=desc");
                    item3 = new ListItem("Theo giá tăng dần", "&orderby=donGia&orderway=asc");
                    item4 = new ListItem("Theo giá giảm dần", "&orderby=donGia&orderway=desc");
                }
                //dua vao danh sach dropdowlist cac tuy chon sap xep
                DropDownSorting.Items.Add(item1);
                DropDownSorting.Items.Add(item2);
                DropDownSorting.Items.Add(item3);
                DropDownSorting.Items.Add(item4);

                //Dua danh sach san pham vao datalist
                GetProductsInManufacturer();
            }
            
        }


        /// <summary>
        /// Tuy vao trang danh xem la trang gi ma chon WebUserControl nay render noi dung trang tuong ung 
        /// ---> do mat code nhieu, chinh sua tren 1 file duy nhat, nhanh chonh chinh xac
        /// </summary>
        public void GetProductsInManufacturer()
        {
            string manufacturerId = Request.QueryString["ManufacturerId"];
            string page = Request.QueryString["Page"];
            //hien thi luon ca thong tin tiem kiem san pham
            string searchString = Request.QueryString["Search"];

            //lay tieu chi sap xep va cach sap xep
            string orderBy = Request.QueryString["orderby"];
            string orderWay = Request.QueryString["orderway"];
            int howManyPages = 1;
            if (page == null)
            {
                page = "1";
            }
            //duong dan daut tieng
            string firstPageUrl = "";
            //ding dang duong dan
            string pagerFormat = "";

            //lay dia chi trang hien tai dang xem
            string currentURL = HttpContext.Current.Request.Url.AbsolutePath.ToString();

            //neu co chuoi tim kiem thi Control nay duoc dung cho trang tim kiem
            if (searchString != null)
            {
                LabelHeader.Text = "Tìm kiếm sản phẩm";
                DropDownSorting.Visible = false;
                string allWords = Request.QueryString["AllWords"];
                DataTable table = product.Search(searchString, allWords, page, out howManyPages);
                if (table.Rows.Count != 0)
                {
                    DlProductsManufacturerList.DataSource = table;
                    DlProductsManufacturerList.DataBind();
                    firstPageUrl = LinkClass.ToSearch(searchString, (allWords.ToUpper() == "TRUE"), "1");
                    pagerFormat = LinkClass.ToSearch(searchString, (allWords.ToUpper() == "TRUE"), "{0}");
                    bottomPager.Show_Pager(Int32.Parse(page), howManyPages, firstPageUrl, pagerFormat, true);
                }
                else
                {
                    bottomPager.Visible = false;
                    LabelHasProduct.Visible = true;
                    LabelHasProduct.Text = "Không tìm thấy sản phẩm.";
                }
            }

            //neu la view san pham theo hang thi dung cho trang hang san xuat
            else if (searchString == null && manufacturerId != null)
            {
                LabelHeader.Text = "Sản phẩm theo hãng";
                firstPageUrl = LinkClass.ToManufacturer(manufacturerId, "1");
                pagerFormat = LinkClass.ToManufacturer(manufacturerId, "{0}");

                DataTable table = product.GetProductsInManufacturer(manufacturerId, page,
                    out howManyPages, orderBy, orderWay);
                DlProductsManufacturerList.DataSource = table;
                DlProductsManufacturerList.DataBind();
                bottomPager.Show_Pager(Int32.Parse(page), howManyPages, firstPageUrl, pagerFormat, true);
            }

            //neu la trang chu cho hien toan bo san pham tai cua hang
            else if (searchString == null && manufacturerId == null && currentURL == "/Home.aspx")
            {
                LabelHeader.Text = "Sản phẩm tại cửa hàng";
                DlProductsManufacturerList.DataSource = product.GetAllProducts(page, out howManyPages, orderBy, orderWay);
                DlProductsManufacturerList.DataBind();
            }

                //neu la trang khuyen mai 
            else if (currentURL == "/KhuyenMai.aspx")
            {
                LabelHeader.Text = "Sản phẩm khuyến mại";
                DlProductsManufacturerList.DataSource = product.GetPromotionalProducts(page, out howManyPages, orderBy, orderBy);
                DlProductsManufacturerList.DataBind();
            }
        }
        /// <summary>
        /// Bat su kien databound, cho hien label khuyen mai chi khi san pham co khuyen mai,
        /// dong thoi hien thi cac thong tin ve thuoc tinh cua san pham
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DlProductsManufacturerList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem)
            {
                // lay doi tuong label thong bao co khuyen mai
                Label deal = (Label)e.Item.FindControl("LabelDeal");

                // lay gia tri xem co khuyen mai hay khong
                string hasDeal = ((DataRowView)e.Item.DataItem).Row.ItemArray[5].ToString();
                
                string strStart = String.Format(((DataRowView)e.Item.DataItem).Row.ItemArray[6].ToString(), "yyyy-MM-dd");
                string strEnd = String.Format(((DataRowView)e.Item.DataItem).Row.ItemArray[7].ToString(), "yyyy-MM-dd");
                DateTime startDate = new DateTime();
                DateTime endDate = new DateTime();
               
               //lay ngay hien tai so san voi ngay bat dau vao ngay ket thuc xem khuyen mai co con hieu luc hay khong

                DateTime now = DateTime.Now;

                //kiem tra xem co khuyen mai hay khong vao thu thi so sanh
                if(strStart != "" && strEnd != "")
                {
                    //lay ngay bat dau khuyen mai
                    //startDate = DateTime.ParseExact(strStart, "yyyy-MM-dd", null);
                    startDate = DateTime.Parse(strStart);
                    //lay ngay ket thuc khuyen mai
                    //endDate = DateTime.ParseExact(strEnd, "yyyy-MM-dd", null);
                    endDate = DateTime.Parse(strEnd);

                    if (hasDeal != "" && DateTime.Compare(startDate, now) < 0 && DateTime.Compare(now, endDate) < 0)
                    {
                        // Neu co khuyen mai thi hien thi hinh anh.
                        deal.Visible = true;
                    }
                }
                
            }

            //lay thong tin ve thuoc tinh cua tung san pham bang cach bat su kien databound
            DataRowView dataRow = (DataRowView)e.Item.DataItem;
            string productID = dataRow["maSanPHam"].ToString();
            DataTable attrTable = product.GetProductAttributes(Int32.Parse(productID));

            string prevAttr = "";
            string attrName, attrValue, attrValueId;

            // lay placeholder chua cac thuoc tinh
            PlaceHolder attrPlaceHolder = (PlaceHolder)e.Item.FindControl("attrPlaceHolder");

            Label attrNameLabel;
            DropDownList attrValueDropDownList = new DropDownList();

            foreach (DataRow row in attrTable.Rows)
            {
                attrName = row["tenThuocTinh"].ToString();
                attrValue = row["giaTriThuocTinh"].ToString();
                attrValueId = row["maGiaTriThuocTinh"].ToString();

                if (attrName != prevAttr)
                {
                    prevAttr = attrName;
                    attrNameLabel = new Label();
                    attrNameLabel.Text = attrName + " ";

                    attrValueDropDownList = new DropDownList();
                    attrPlaceHolder.Controls.Add(attrNameLabel);
                    attrPlaceHolder.Controls.Add(attrValueDropDownList);
                }
                attrValueDropDownList.Items.Add(new ListItem(attrValue, attrValueId));
            }

        }

        /// <summary>
        /// Them san pham vao gio hang o trang liet ke danh sach san pham
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LinkAddToCart_Click(object sender, EventArgs e)
        {
            //Lay linkbutton duoc click vao 
            LinkButton myButton = sender as LinkButton;
            //Lay commandArgument duoc dua vao trong file aspx
            string id = myButton.CommandArgument.ToString();

            //Lay datalistItem chua linkbutton qua thuoc tinh NamingCOntainer
            DataListItem datalistItem = (DataListItem)myButton.NamingContainer;
            //Lay placeHolder chua cac control thuoc tinh trong DataListItem
            PlaceHolder attr = (PlaceHolder)DlProductsManufacturerList.Items[datalistItem.ItemIndex].FindControl("attrPlaceHolder");
            string options = "";

            foreach (Control ctr in attr.Controls)
            {
                //lay ten loai thuoc tinh
                if (ctr is Label)
                {
                    Label lb = (Label)ctr;
                    options += lb.Text;
                }
                //lay gia tri cua thuoc tinh
                if (ctr is DropDownList)
                {
                    DropDownList dr = (DropDownList)ctr;
                    options += dr.Items[dr.SelectedIndex] + "; ";
                }
            }

            ShoppingCart shop = new ShoppingCart();
            shop.AddItem(id, options);
        }

    }
}